//
//  ViewController.m
//  UITableView提高用户体验
//
//  Created by 青梅睿创公司 on 2018/2/12.
//  Copyright © 2018年 青梅睿创公司. All rights reserved.
//

#import "ViewController.h"

#import <AFNetworking.h>
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>

#import "CustomTableViewCell.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSInteger page;
}
@property (nonatomic, strong) UITableView * tableView;

@property (nonatomic, strong) NSMutableArray * dataArr;

@property (nonatomic, strong) UIImageView * imageV;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self.view addSubview:self.tableView];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self getNewData];
    }];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getMoreData];
    }];
    
    self.imageV = [[UIImageView alloc] init];
}

- (void)getNewData{
    
    page = 1;
    [self loadData];
}
- (void)getMoreData{
    page ++;
    [self loadData];
}

- (void)loadData{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", nil];
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    /*
     "city_id" = 1;
     p = 1;
     */
    NSString * pageStr = [NSString stringWithFormat:@"%lu", page];
    dic[@"city_id"] = @"1";
    dic[@"p"] = pageStr;
    [manager POST:@"http://lvyou.qmnet.com.cn/index.php/spot/index" parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress:%@", uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        NSLog(@"返回数据：%@", responseObject);
        NSArray * arr = responseObject[@"data"];
        NSLog(@"arr:%@", arr);
        if (page == 1) {    // 下拉刷新
            [self.dataArr removeAllObjects];
            [self.dataArr addObjectsFromArray:arr];
        }else{  // 上拉加载
            if (arr.count > 0) {
                [self.dataArr addObjectsFromArray:arr];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            //
            
        }
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error:%@", error);
    }];
}

#pragma mark --- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CustomTableViewCell * cell = [CustomTableViewCell cellWithTableView:tableView];
    NSDictionary * dic = self.dataArr[indexPath.row];
    NSString * picStr = dic[@"pic"];
    [cell.picView sd_setImageWithURL:[NSURL URLWithString:picStr]];
    
    NSArray * visibleRows = [tableView indexPathsForVisibleRows];
    NSLog(@"count:%lu", visibleRows.count);
    NSInteger nextRow = indexPath.row + visibleRows.count;
    if (nextRow < self.dataArr.count) {
        NSLog(@"nextRow:%lu", nextRow);
        NSDictionary * nextDic = self.dataArr[indexPath.row];
        NSString * nextPicStr = nextDic[@"pic"];
        [self.imageV sd_setImageWithURL:[NSURL URLWithString:nextPicStr]];
    }
    
    
    NSInteger row = indexPath.row;
    if (self.dataArr.count - row < visibleRows.count) {
        [self.tableView.mj_footer beginRefreshing];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableView *)tableView{
    if (_tableView == nil) {
        CGFloat statusH = [UIApplication sharedApplication].statusBarFrame.size.height;
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, statusH, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}
- (NSMutableArray *)dataArr{
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray array];
        
    }
    //
    return _dataArr;
}

@end
